package com.huawei.app.demo.service;

import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

/**
 * 处理悬浮窗口的拖拽事件
 *
 * @since 2021-01-15
 */
public class FloatingOnTouchListener implements View.OnTouchListener {

    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private View rootView;
    private int x;
    private int y;

    public FloatingOnTouchListener(WindowManager windowManager, WindowManager.LayoutParams layoutParams, View rootView) {
        this.windowManager = windowManager;
        this.layoutParams = layoutParams;
        this.rootView = rootView;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                x = (int)event.getRawX();
                y = (int)event.getRawY();
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                int newX = (int)event.getRawX();
                int newY = (int)event.getRawY();
                int movedX = newX - x;
                int movedY = newY - y;
                layoutParams.x = layoutParams.x + movedX;
                layoutParams.y = layoutParams.y + movedY;
                x = newX;
                y = newY;
                windowManager.updateViewLayout(rootView, layoutParams);
                break;
            }
            default: {
                break;
            }
        }
        return false;
    }
}
